var menu, toolbar, mainPanel, loginWindow, statusBar, selectedLabyrinth;

Ext.onReady(function() {
    
    var startLabyrinthButton = new Ext.Button({text: 'Start Labyrinth', iconCls: 'start', disabled: true, handler: function() {
            if(selectedLabyrinth)
                document.location = siteRoot + 'labyrinth/' + selectedLabyrinth + '/';
        }
    });
    
    // Build the menu system based on whether or not we're logged in
    if(loginStatus != '') {
        toolbarItems = [
            startLabyrinthButton,
            '->',
            {
                text: 'Administration',
                iconCls: 'administration',
                handler: function() {window.location = siteRoot + 'administration/labyrinths/';}
            },
            '-',
            {
                text: 'Reports',
                iconCls: 'reports',
                handler: function() {window.location = siteRoot + 'reports/';}
            },
            '-',
            {
                text: 'Logout',
                iconCls: 'logout',
                handler: logout
            }
        ]
    } else {
        toolbarItems = [
            startLabyrinthButton,
            '->',
            {
                text: 'Reports',
                iconCls: 'reports',
                handler: function() {window.location = siteRoot + 'reports/';}
            },
            '-',
            {
                id: 'loginButton',
                text: 'Login',
                iconCls: 'login',
                handler: login
            }
        ]
    }

    // Build the toolbar with its two entries
    toolbar = new Ext.Toolbar({
        height: 27,
        items: toolbarItems
    });
    
    // Build the popup login window
    loginWindow = new Ext.Window({
        id          : 'loginWindow',
        applyTo     : 'loginBlock',
        draggable   : false,
        layout      : 'fit',
        width       : 350,
        height      : 150,
        closable    : false,
        plain       : true,
        iconCls     : 'loginPanel',
        buttons: [{
            text     : 'Login',
            handler  : function(){
                Ext.getDom('loginForm').submit();
            }
        },{
            text     : 'Cancel',
            handler  : function(){
                loginWindow.hide('loginButton');
            }
        }]
    });
    
    Ext.get('loginForm').on('submit', function(){
        var loadMask = new Ext.LoadMask(Ext.getBody(), {msg:"Logging in..."});
        loadMask.show();
    });
    
    var labyrinthData = new Ext.data.Store({
        // load using HTTP
        url: siteRoot+'labyrinths/data/',

        // the return will be XML, so lets set up a reader
        reader: new Ext.data.XmlReader({
               // records will have an "Item" tag
               record: 'labyrinth',
               id: 'ASIN'
           }, ['id', 'name', 'type', 'access', 'keywords', 'credits', 'breadcrumbs', 'skin', 'time_limit'])
    });

    var labyrinthGrid = new Ext.grid.GridPanel({
        title: 'Labyrinths',
        store: labyrinthData,
        columns: [
            {header: 'Name', width: 120, sortable: true, dataIndex: 'name'},
            {header: 'Type', width: 90, sortable: true, dataIndex: 'type'},
            {header: 'Access', width: 90, sortable: true, dataIndex: 'access'}
        ],
        viewConfig: {
            forceFit: true
        },
        region: 'center',
        frame: true,
        margins: '5 0 5 5',
        loadMask: new Ext.LoadMask(Ext.getBody(), {msg:"Retrieving list of labyrinths..."})
    });
 
    var labyrinthDetailPanel = new Ext.Panel({
        id: 'labyrinthDetailPanel',
        title: 'Details',
        width: 250,
        height: 220,
        bodyCfg: {cls: 'panelBody labyrinthPanel'},
        region: 'east',
        frame: true,
        margins: '5 5 5 5'
    });

    // Build the application viewport which will house all other components
    viewport = new Ext.Viewport({
        title: 'OpenLabyrinth',
        id: 'viewport',
        layout:'border',
        items: [new Ext.Panel({
            border: false,
            region:'north',
            tbar: toolbar
        }), labyrinthGrid, labyrinthDetailPanel]
    });
    
    // define a template to use for the detail view
    var labyrinthTplMarkup = [
        '<table id="labyrinthDetails">',
        '<tr><td><strong>Name:</strong></td><td>{name}</td>',
        '<tr><td><strong>Type:</strong></td><td>{type}</td>',
        '<tr><td><strong>Time Limit:</strong></td><td>{time_limit}</td>',
        '<tr><td><strong>Access:</strong></td><td>{access}</td>',
        '<tr><td><strong>Keywords:</strong></td><td>{keywords}</td>',
        '<tr><td><strong>Credits:</strong></td><td>{credits}</td>',
        '<tr><td><strong>Breadcrumbs:</strong></td><td>{breadcrumbs}</td>',
        '<tr><td><strong>Skin:</strong></td><td>{skin}</td>',
        '</table>'
    ];
    var labyrinthTpl = new Ext.Template(labyrinthTplMarkup);
    
    // Whenever a labyrinth is selected, this function updates the details
    // field with the properties of the selected labyrinth.
    labyrinthGrid.getSelectionModel().on('rowselect', function(sm, rowIdx, r) {
        var labyrinthDetailPanel = Ext.getCmp('labyrinthDetailPanel');
        labyrinthTpl.overwrite(labyrinthDetailPanel.body, r.data);
        selectedLabyrinth = r.data.id;
        startLabyrinthButton.enable();
    });
    
    // Whenever a labyrinth is deselected, this function updates the details
    // field with the properties of the selected labyrinth.
    labyrinthGrid.getSelectionModel().on('rowdeselect', function(sm, rowIdx, r) {
        startLabyrinthButton.disable();
        selectedLabyrinth = false;
    });
    
    // Draw the application
    viewport.render('pageContent');

    labyrinthData.load();
});

/*
** Callback functions for the menu entries
*/

function login() {
    
    // Center the login panel on the screen
    Ext.get('loginTable').center(loginWindow.body);
    
    loginWindow.show('loginButton');
    Ext.get('id_username').focus(1000);
}

function logout() {
    window.location = siteRoot + 'logout/';
}
